package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
//@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String url = request.getRequestURL().toString();
        if(url.contains("login")){
            log.info("登录接口放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("token");
        if(token==null||token.length() == 0){
            log.info("token为空或者为null");
            response.setStatus(401);
            return;
        }
        try {
            JwtUtils.parseJWT(token);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }catch (Exception e){
            response.setStatus(401);
        }
    }
}
